package by.yakusekmaxim.bookgid.services.impl;

import java.util.List;

import javax.inject.Inject;
import javax.persistence.metamodel.SingularAttribute;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import by.yakusekmaxim.bookgid.dataaccess.AuthorDao;
import by.yakusekmaxim.bookgid.dataaccess.BookDao;
import by.yakusekmaxim.bookgid.dataaccess.ImageDao;
import by.yakusekmaxim.bookgid.datamodel.Author;
import by.yakusekmaxim.bookgid.datamodel.Author_;
import by.yakusekmaxim.bookgid.datamodel.Book;
import by.yakusekmaxim.bookgid.datamodel.Book_;
import by.yakusekmaxim.bookgid.datamodel.Image;
import by.yakusekmaxim.bookgid.services.ImageService;

@Service
public class ImageServiceImpl implements ImageService {
    private static final Logger LOGGER = LoggerFactory.getLogger(ImageServiceImpl.class);

    @Inject
    private ImageDao dao;
    
	@Inject
	private BookDao daoBook;
	
	@Inject
	private AuthorDao daoAuthor;


    @Value(value="${rootImagesFolfer}")
	private String rootFolder;
    
    @Override
    public Image get(Long id) {
        Image entity = dao.getById(id);
        return entity;
    }

    @Override
    public void saveOrUpdate(Image image) {
        if (image.getId() == null) {
            LOGGER.debug("Save new: {}", image);
            dao.insert(image);
        } else {
            LOGGER.debug("Update: {}", image);
            dao.update(image);
        }
    }

    @Override
    public void delete(Image image) {
		List<Book> bookList = daoBook.getAllBooks(Book_.image, image);
		if (bookList != null) {
			for (Book book : bookList) {
				book.setImage(null);
				LOGGER.debug("Update: {}", book);
				daoBook.update(book);
			}
		}
		
		List<Author> authorList = daoAuthor.getAllAuthor(Author_.image, image);
		if (authorList != null) {
			for (Author author : authorList) {
				author.setImage(null);
				LOGGER.debug("Update: {}", author);
				daoAuthor.update(author);
			}
		}
		
        LOGGER.debug("Remove: {}", image);
        dao.delete(image.getId());

    }

    @Override
    public void deleteAll() {
        LOGGER.debug("Remove all images");
        dao.deleteAll();
    }

	@Override
	public List<Image> getAllImages(SingularAttribute<Image, ?> attr,
			boolean ascending, int startRecord, int pageSize) {
		return dao.getAllImages(attr, ascending, startRecord, pageSize);
	}

	@Override
	public String getRootFolder() {
		return rootFolder;
	}

	@Override
	public Long getCount() {
		return dao.getCount();
	}

	@Override
	public List<Image> getAll() {
		
		LOGGER.debug("Get all Genres");
		return dao.getAll();
	}

}
